package com.example.wangzh.mytest.base;

import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.example.wangzh.mytest.R;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by wangzh on 2017/10/19.
 */

public class BaseActivity<B extends ViewBinding> extends AppCompatActivity {
    protected B mBinding;

    @SuppressWarnings({"unchecked", "ConstantConditions"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            Type genericSuperclass = getClass().getGenericSuperclass();
            Class<?> bindingClass = (Class<?>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
            Method method = bindingClass.getDeclaredMethod("inflate", LayoutInflater.class);
            mBinding = (B) method.invoke(null, getLayoutInflater());
            setContentView(mBinding.getRoot());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        initView();
    }

    @Deprecated
    protected int getLayout() {
        return R.layout.activity_main;
    }

    protected void initView() {
    }
}
